package org.springblade.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import org.springblade.common.utils.UeditorUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Base64Util;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.app.entity.Article;
import org.springblade.modules.app.entity.SearchTag;
import org.springblade.modules.app.service.IArticleService;
import org.springblade.modules.app.service.ISearchTagService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 文章列表 控制器
 *
 * @author kingk
 */
@RestController
@RequestMapping("blade-app/article")
public class ArticleController extends BladeController {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private BladeRedis bladeRedis;
    @Autowired
    private ISearchTagService searchTagService;


    /**
     * 分页 文章列表
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入article")
    public R<IPage<Article>> list(Page page, Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<Article>();
        if (!StringUtils.isEmpty(params.getTitle())) {
            queryWrapper.and(wrapper -> wrapper.like(Article::getTitle, params.getTitle()));
        }
        if (!StringUtils.isEmpty(params.getType())) {
            queryWrapper.and(wrapper -> wrapper.eq(Article::getType, params.getType()));
        }
        queryWrapper.orderByDesc(Article::getCtime);
        IPage<Article> pages = articleService.page(page, queryWrapper);

        if (!StringUtils.isEmpty(params.getTitle())) {
            SearchTag searchTag = new SearchTag();
            searchTag.setStag(params.getTitle());
            searchTag.setCtime(new Date());
            searchTagService.save(searchTag);
        }
        return R.data(pages);
    }

    /**
     * 自定义分页 文章列表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入article")
    public R<IPage<Article>> page(Page page, Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<Article>();
        if (!StringUtils.isEmpty(params.getTitle())) {
            queryWrapper.and(wrapper -> wrapper.like(Article::getTitle, params.getTitle()));
        }
        if (!StringUtils.isEmpty(params.getType())) {
            queryWrapper.and(wrapper -> wrapper.eq(Article::getType, params.getType()));
        }
        queryWrapper.orderByDesc(Article::getCtime);
        IPage<Article> pages = articleService.page(page, queryWrapper);

        if (!StringUtils.isEmpty(params.getTitle())) {
            SearchTag searchTag = new SearchTag();
            searchTag.setStag(params.getTitle());
            searchTag.setCtime(new Date());
            searchTagService.save(searchTag);
        }

        return R.data(pages);
    }

    /**
     * 新增 文章列表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入article")
    public R save(@RequestBody Article article) {
        BladeUser user = AuthUtil.getUser();
        Dept dept = deptService.getById(user.getDeptId());
        User user1 = userService.getById(user.getUserId());
        article.setUserid(user.getUserId());


        article.setContext(Base64Util.decode(article.getContext()));
        //FIXME 富文本 转换为纯文本
        article.setClitext(UeditorUtil.getTextByHtml(article.getContext()));

        return R.status(articleService.save(article));
    }

    /**
     * 修改 文章列表
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改", notes = "传入article")
    public R update(@RequestBody Article article) {
        if (StringUtils.isEmpty(article.getId())) {
            return R.fail("主键不能为空");
        }
        article.setContext(Base64Util.decode(article.getContext()));
        //FIXME 富文本 转换为纯文本
        article.setClitext(UeditorUtil.getTextByHtml(article.getContext()));

        return R.status(articleService.updateById(article));
    }

    /**
     * 新增或修改 文章列表
     */
    @PostMapping("/submit")
    @ApiOperation(value = "新增或修改", notes = "传入article")
    public R submit(@RequestBody Article article) {
        BladeUser bladeUser = AuthUtil.getUser();
////TODO 文章base64测试
        article.setPushtime(new Date());
        article.setUserid(bladeUser.getUserId());
        article.setDeptid(bladeUser.getDeptId());
        article.setCtime(new Date());

        article.setContext(Base64Util.decode(article.getContext()));

        //FIXME 富文本 转换为纯文本
        article.setClitext(UeditorUtil.getTextByHtml(article.getContext()));

        return R.status(articleService.saveOrUpdate(article));
    }


    /**
     * 删除 文章列表
     */
    @PostMapping("/remove")
    @ApiOperation(value = "删除", notes = "传入ids")
    public R remove(@RequestParam String ids) {
        return R.status(articleService.removeByIds(Func.toLongList(ids)));
    }

    ///////////////////////////////////////////////FIXME APP端接口////////////////////////////////////

    /**
     * app端搜索
     *
     * @param page
     * @param params
     * @return
     */
    @GetMapping("/pageSearch")
    public R<IPage<Article>> pageSearch(Page page, Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<Article>();
        if (!StringUtils.isEmpty(params.getTitle())) {
            queryWrapper.and(wrapper -> wrapper.like(Article::getTitle, params.getTitle()));
        }
        if (!StringUtils.isEmpty(params.getType())) {
            queryWrapper.and(wrapper -> wrapper.eq(Article::getType, params.getType()));
        }
        queryWrapper.orderByDesc(Article::getCtime);
        IPage<Article> pages = articleService.page(page, queryWrapper);

        if (!StringUtils.isEmpty(params.getTitle())) {
            SearchTag searchTag = new SearchTag();
            searchTag.setStag(params.getTitle());
            searchTag.setCtime(new Date());
            searchTagService.save(searchTag);
        }

        return R.data(pages);
    }

    ////////////////////////主页文章搜索 热搜的文章标题列表
    @GetMapping("/pageSearchHot")
    public R pageSearchHot(Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<Article>();
        if (!StringUtils.isEmpty(params.getTitle())) {
            queryWrapper.and(wrapper -> wrapper.like(Article::getTitle, params.getTitle()));
        }
        if (!StringUtils.isEmpty(params.getType())) {
            queryWrapper.and(wrapper -> wrapper.eq(Article::getType, params.getType()));
        }
        queryWrapper.orderByDesc(Article::getReadno);
        queryWrapper.last("limit 5");
        List<Article> articleList = articleService.list(queryWrapper);
        return R.data(articleList);
    }

    /**
     * 管理中心 文章管理_理论学习
     *
     * @param page
     * @param params
     * @return
     */
    @GetMapping("/pageByApp")
    public R<IPage<Article>> pageByApp(Page page, Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.and(wrapper -> wrapper.like(Article::getTjfalg, "2"));
//		queryWrapper.and(wrapper -> wrapper.like(Article::getAppflag, "2"));
        queryWrapper.orderByDesc(Article::getCtime);
        IPage<Article> pages = articleService.page(page, queryWrapper);
        return R.data(pages);
    }

    /////////////////FIXME 我发布的文章
    @GetMapping("/pageByUser")
    public R<IPage<Article>> pageByUser(Page page, Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.and(wrapper -> wrapper.like(Article::getAppflag, "2"));
        //TODO  当前用户更好的获取方式 除token解析外
//		queryWrapper.and(wrapper -> wrapper.like(Article::getUserid, "2"));

        BladeUser user = AuthUtil.getUser();
        Dept dept = deptService.getById(user.getDeptId());
        User user1 = userService.getById(user.getUserId());
//        queryWrapper.and(wrapper -> wrapper.like(Article::getUserid, user.getUserId()));

        queryWrapper.orderByDesc(Article::getCtime);
        IPage<Article> pages = articleService.page(page, queryWrapper);
        return R.data(pages);
    }

    @PostMapping("/saveByApp")
    @ApiOperation(value = "发布", notes = "传入article")
    public R saveByApp(@RequestBody Article article) {
        BladeUser user = AuthUtil.getUser();
//        DeptDp dept = deptService.getById(user.getDeptId());
//        User user1 = userService.getById(user.getUserId());

        article.setAppflag("2");
        article.setPushtime(new Date());
        article.setCtime(new Date());
        article.setDeptid(user.getDeptId());
        article.setUserid(user.getUserId());

        //FIXME 富文本 转换为纯文本
        String editorContext = Base64Util.decode(article.getContext());
        article.setContext(editorContext);

        article.setClitext(UeditorUtil.getTextByHtml(editorContext));


        return R.status(articleService.save(article));
    }

    /**
     * 修改 文章列表
     */
    @PostMapping("/updateByApp")
    @ApiOperation(value = "修改", notes = "传入article")
    public R updateByApp(@RequestBody Article article) {
        if (StringUtils.isEmpty(article.getId())) {
            return R.fail("ID Must not be null");
        }
        String editorContext = Base64Util.decode(article.getContext());
        article.setContext(editorContext);

        //FIXME 富文本 转换为纯文本
        article.setClitext(UeditorUtil.getTextByHtml(editorContext));


        return R.status(articleService.updateById(article));
    }

    //APP端删除
    @PostMapping("/removeByApp")
    public R removeByApp(Article article) {
        if (StringUtils.isEmpty(article.getId())) {
            return R.fail("ID Must not be null");
        }
        return R.status(articleService.removeById(article.getId()));
    }

    @PostMapping("/updateTjByApp")
    @ApiOperation(value = "推荐", notes = "传入article")
    public R updateTjByApp(Article article) {
        if (StringUtils.isEmpty(article.getId())) {
            return R.fail("ID Must not be null");
        }
        article.setTjfalg("2");
        return R.status(articleService.updateById(article));
    }

    ///////////////////////////FIXME 银龄动态更多  只获取tjflag为2的 推荐内容//////////////////////
    @GetMapping("/getNewOneArticle")
    public R<Article> getNewOneArticle(Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //只查询推荐到银龄动态的
        queryWrapper.and(wrapper -> wrapper.like(Article::getTjfalg, "2"));
        queryWrapper.orderByDesc(Article::getCtime);
        List<Article> list = articleService.list(queryWrapper);
        if (list.isEmpty()) {
            return R.fail("暂无数据");
        }
        return R.data(list.get(0));
    }

    @GetMapping("/getMoreArticle")
    public R<IPage<Article>> getMoreArticle(Page page, Article params) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.and(wrapper -> wrapper.like(Article::getTjfalg, "2"));
//		queryWrapper.and(wrapper -> wrapper.like(Article::getAppflag, "2"));
        queryWrapper.orderByDesc(Article::getCtime);
        IPage<Article> pages = articleService.page(page, queryWrapper);
        return R.data(pages);
    }


    /////查询服务中心发的所有文章
    @GetMapping("/getArticleByDept")
    public R<List<Article>> getArticleByDept(Article params) {
        if (StringUtils.isEmpty(params.getDeptid())) {
            return R.fail("DeptDp Must not be null");
        }
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq(Article::getDeptid, params.getDeptid()));
        queryWrapper.orderByDesc(Article::getCtime);
        List<Article> list = articleService.list(queryWrapper);
        return R.data(list);
    }


    // 查询服务中心下的的手机端发布的文章  对应其他
    @GetMapping("/getArticleByDeptApp")
    public R<IPage<Article>> getArticleByDeptApp(Page page, Article params) {
        if (StringUtils.isEmpty(params.getDeptid())) {
            return R.fail("DeptDp Must not be null");
        }
//		LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<Article>();
//		queryWrapper.and(wrapper -> wrapper.like(Article::getTjfalg, "1"));
//		queryWrapper.and(wrapper -> wrapper.like(Article::getAppflag, "1"));
//		queryWrapper.orderByDesc(Article::getCtime);
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq(Article::getDeptid, params.getDeptid()));
        queryWrapper.and(wrapper -> wrapper.eq(Article::getAppflag, "2"));
        queryWrapper.orderByDesc(Article::getCtime);
        IPage<Article> pages = articleService.page(page, queryWrapper);
        return R.data(pages);
    }


    @GetMapping("/getArticleInfo")
    public R<Article> getArticleInfo(Article article) {
        Article detail = articleService.getById(article.getId());
        return R.data(detail);
    }
}
